import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class test {
    private static final String DATA_FILE = "data.txt";
    private static final String STUDS_FILE = "studs.txt";
    private static final String TEMP_FILE = "temp.txt";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;

        while (true) {
            System.out.println("\n请选择操作：");
            System.out.println("(0) 读取全部内容");
            System.out.println("(1) 读取学生姓名和分数到文件");
            System.out.println("(2) 选出分数最高的学生");
            System.out.println("(3) 计算每个班级的平均分");
            System.out.println("(4) 查询成绩");
            System.out.println("(5) 修改成绩");
            System.out.println("(-1) 退出");
            System.out.print("请输入选项：");
            choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 0:
                    readAll();
                    break;
                case 1:
                    extractNamesAndScores();
                    break;
                case 2:
                    printHighestScore();
                    break;
                case 3:
                    calculateAverageScores();
                    break;
                case 4:
                    queryScore();
                    break;
                case 5:
                    modifyScore();
                    break;
                case -1:
                    System.out.println("程序已退出。");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选项，请重新选择。");
                    break;
            }
        }
    }

    private static void readAll() {
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void extractNamesAndScores() {
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE));
             BufferedWriter writer = new BufferedWriter(new FileWriter(STUDS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(":");
                writer.write(parts[0].trim() + ":" + parts[1].split(",")[1].trim());
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printHighestScore() {
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
            double highestScore = 0;
            String highestName = "";
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(":");
                int score = Integer.parseInt(parts[1].split(",")[1].trim());
                if (score > highestScore) {
                    highestScore = score;
                    highestName = parts[0].trim();
                }
            }
            System.out.println(highestName + ":" + highestScore);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void calculateAverageScores() {
        Map<String, List<Integer>> classScores = new HashMap<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(":");
                String className = parts[1].split(",")[0].trim();
                int score = Integer.parseInt(parts[1].split(",")[1].trim());
                classScores.computeIfAbsent(className, k -> new ArrayList<>()).add(score);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (Map.Entry<String, List<Integer>> entry : classScores.entrySet()) {
            double average = entry.getValue().stream().mapToInt(Integer::intValue).average().orElse(0.0);
            System.out.printf("%s:%.2f%n", entry.getKey(), average);
        }
    }

    private static void queryScore() {
        System.out.print("请输入学生姓名：");
        String name = new Scanner(System.in).nextLine();
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith(name + ":")) {
                    String[] parts = line.split(":");
                    System.out.println(parts[0] + " " + parts[1].split(",")[0].trim() + " " + parts[1].split(",")[1].trim());
                    return;
                }
            }
            System.out.println("未找到该学生。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void modifyScore() {
        System.out.print("请输入学生姓名：");
        String name = new Scanner(System.in).nextLine();
        System.out.print("请输入新分数：");
        double newScore = new Scanner(System.in).nextDouble();
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine(); // 消费换行符

        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith(name + ":")) {
                    String[] parts = line.split(",");
                    line = name + ":" + parts[0].trim() + "," + newScore;
                }
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(TEMP_FILE))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 替换原文件
        try {
            Files.delete(Paths.get(DATA_FILE));
            Files.move(Paths.get(TEMP_FILE), Paths.get(DATA_FILE));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}